import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Dictionary } from '../models/dictionary.entity';
import { DictionaryItem } from '../models/dictionary-item.entity';

@Injectable()
export class DictionaryService {
  constructor(
    @InjectRepository(Dictionary)
    private dictionaryRepository: Repository<Dictionary>,
    @InjectRepository(DictionaryItem)
    private dictionaryItemRepository: Repository<DictionaryItem>,
  ) {}

  findAll(): Promise<Dictionary[]> {
    return this.dictionaryRepository.find({ relations: ['items'] });
  }

  findOne(id: number): Promise<Dictionary | null> {
    return this.dictionaryRepository.findOne({
      where: { id },
      relations: ['items'],
    });
  }

  async create(dictData: Partial<Dictionary>): Promise<Dictionary> {
    const dictionary = this.dictionaryRepository.create(dictData);

    // 处理items关联
    if (dictData.items) {
      const items = dictData.items.map((item) =>
        this.dictionaryItemRepository.create(item),
      );
      await this.dictionaryItemRepository.save(items);
      dictionary.items = items;
    }

    return this.dictionaryRepository.save(dictionary);
  }

  async update(
    id: number,
    dictData: Partial<Dictionary>,
  ): Promise<Dictionary | null> {
    const dictionary = await this.findOne(id);
    if (!dictionary) {
      return null;
    }

    // 更新基本字段
    this.dictionaryRepository.merge(dictionary, dictData);

    // 处理items关联 (简化版：先删除旧的，再添加新的)
    if (dictData.items) {
      // 删除旧的items
      if (dictionary.items) {
        await this.dictionaryItemRepository.remove(dictionary.items);
      }
      // 添加新的items
      const items = dictData.items.map((item) =>
        this.dictionaryItemRepository.create({ ...item, dictionary }),
      );
      await this.dictionaryItemRepository.save(items);
      dictionary.items = items;
    }

    return this.dictionaryRepository.save(dictionary);
  }

  async remove(id: number): Promise<Dictionary | null> {
    const dictionary = await this.findOne(id);
    if (!dictionary) {
      return null;
    }

    // 先删除关联的items
    if (dictionary.items) {
      await this.dictionaryItemRepository.remove(dictionary.items);
    }

    return this.dictionaryRepository.remove(dictionary);
  }
}
